package cn.iocoder.yudao.module.book.service.users;

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import cn.iocoder.yudao.module.book.controller.admin.users.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.users.userDTODO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.book.constants.UserConstants;

import cn.iocoder.yudao.module.book.dal.mysql.users.userDTOMapper;

import java.time.LocalDateTime;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

/**
 * 用户 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class userDTOServiceImpl implements userDTOService {

    @Resource
    private userDTOMapper userDTOMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public userDTODO createUserIfAbsent(String mobile, String registerIp, Integer terminal) {
        // 用户已经存在
        userDTODO user = userDTOMapper.selectByMobile(mobile);
        if (user != null) {
            return user;
        }
        // 用户不存在，则进行创建
        return createUser(mobile, null, null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public userDTODO createUser(String mobile, String nickname, String avatar) {
        userDTODO user = new userDTODO();
        user.setMobile(mobile);
        user.setNickname(nickname != null ? nickname : "用户_" + RandomStringUtils.randomAlphanumeric(6));
        user.setAvatarUrl(avatar != null ? avatar : UserConstants.DEFAULT_AVATAR_URL);
        user.setCreateTime(LocalDateTime.now());
        userDTOMapper.insert(user);
        return user;
    }

    @Override
    public void updateUserLogin(Long id) {
        userDTOMapper.updateById(new userDTODO().setUserId(id));
    }

    @Override
    public Long createuserDTO(userDTOSaveReqVO createReqVO) {
        // 插入
        userDTODO userDTO = BeanUtils.toBean(createReqVO, userDTODO.class);
        userDTOMapper.insert(userDTO);
        // 返回
        return userDTO.getUserId();
    }

    @Override
    public void updateuserDTO(userDTOSaveReqVO updateReqVO) {
        // 校验存在
        validateuserDTOExists(updateReqVO.getUserId());
        // 更新
        userDTODO updateObj = BeanUtils.toBean(updateReqVO, userDTODO.class);
        userDTOMapper.updateById(updateObj);
    }

    @Override
    public void deleteuserDTO(Integer id) {
        // 校验存在
        validateuserDTOExists(id);
        // 删除
        userDTOMapper.deleteById(id);
    }

    private void validateuserDTOExists(Integer id) {
        if (userDTOMapper.selectById(id) == null) {
            throw exception(USER_DTO_NOT_EXISTS);
        }
    }

    @Override
    public userDTODO getuserDTO(Long id) {
        return userDTOMapper.selectById(id);
    }

    @Override
    public PageResult<userDTODO> getuserDTOPage(userDTOPageReqVO pageReqVO) {
        return userDTOMapper.selectPage(pageReqVO);
    }

    @Override
    public Long getCurrentUserId() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser != null) {
            return loginUser.getId();
        }
        return null;
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if (authentication == null || !authentication.isAuthenticated()) {
//            throw new RuntimeException("用户未登录");
//        }
////        System.out.println("authentication = " + authentication);
//
//        // 假设你将用户信息存储在 UserDetails 中
//        Object principal = authentication.getPrincipal();
////        System.out.println("principal = " + principal);
//        if (principal instanceof UserDetails) {
//            String username = ((UserDetails) principal).getUsername();
////            System.out.println("username = " + username);
//            // 根据 username 查询数据库获取 userId
//            return getUserIdByUsername(username);
//
//        }else if(principal instanceof LoginUser){
//            return ((LoginUser) principal).getId();
//        } else {
//            throw new RuntimeException("无法识别用户身份");
//        }
    }

    public Long getUserIdByUsername(String username) {
        return userDTOMapper.selectByUsername(username);
    }


    public userDTODO getByOpenId(String openid) {
        return userDTOMapper.selectByOpenId(openid);
    }

    public userDTODO registerWeChatUser(String openid, String sessionKey) {
        userDTODO user = new userDTODO();
        user.setOpenid(openid);
        user.setSessionKey(sessionKey);
        user.setNickname("微信用户_" + RandomStringUtils.randomAlphanumeric(6));
        user.setAvatarUrl(UserConstants.DEFAULT_AVATAR_URL);
        user.setCreateTime(LocalDateTime.now());
        userDTOMapper.insert(user);
        return user;
    }

    @Override
    public void updateMyProfile(Long userId, String nickname, String avatarUrl, String mobile) {
        userDTODO update = new userDTODO();
        update.setUserId(userId);
        update.setNickname(nickname);
        update.setAvatarUrl(avatarUrl);
        update.setMobile(mobile);
        userDTOMapper.updateById(update);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deactivateUser(Long userId) {
        // 校验用户存在
        if (userDTOMapper.selectById(userId) == null) {
            throw exception(USER_DTO_NOT_EXISTS);
        }
        
        // 物理删除用户相关数据（按照外键约束的顺序删除）
        // 1. 删除用户的打卡记录
        userDTOMapper.deleteUserClockIns(userId);
        
        // 2. 删除用户的音频记录
        userDTOMapper.deleteUserAudios(userId);
        
        // 3. 删除用户的书架记录
        userDTOMapper.deleteUserBookshelves(userId);
        
        // 4. 删除用户的阅读记录
        userDTOMapper.deleteUserReadingRecords(userId);
        
        // 5. 删除用户的收藏记录
        userDTOMapper.deleteUserCollects(userId);
        
        // 6. 删除用户的班级关联
        userDTOMapper.deleteUserClasses(userId);
        
        // 7. 最后删除用户基本信息
        userDTOMapper.physicalDeleteUser(userId);
    }


}